import React, { Component } from 'react';
import ReactDom from 'react-dom';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      listdeta: ["大娃","二娃","三娃","四娃"],
      title: ''
    }
  }

componentDidMount() {
  const list = localStorage.getItem("todolist");
  if (list && list.length !== 0) {
    this.setState({
      listdeta:list.split(",")
    })
  }
}

// 监听以及储存input框内容
inputFn = evt => {
  this.setState({
    title : evt.target.value
  })

}
// 点击添加数据
addItem = () => {
  if(this.state.title === ''){
    alert("请输入内容！")
    return;
  }
  this.setState({
    listdeta : [...this.state.listdeta,this.state.title],
    title: ''
  })
  localStorage.setItem('listdeta',[...this.state.listdeta,this.state.title]);
}
// 点击删除
remove = (index) => {
  let list = [...this.state.listdeta];
  list.splice(index,1);
  this.setState({
    listdeta : list
  })
  localStorage.setItem('listdeta',list);
}
  render() {
    return (
      <div>
        <input onInput={this.inputFn} value={this.state.title} /><button onClick={this.addItem}>添加</button>
        <ul style={{ listStyle:'none' }}>
          {
            this.state.listdeta.map((item,index) => {
              return<TodoItem item={item} key={index} index={index} remove={this.remove} />
            })
          }
        </ul>
      </div>
    );
  }
}
// TodoItme 组件
class TodoItem extends Component {
  remove = () => {
    this.props.remove(this.props.index);
  }
  render() {
    return (
      <li>
        {this.props.item}
        <button onClick={this.remove}>删除</button>
      </li>
    )
  }
}
ReactDom.render(<App/>,document.getElementById("root"))

export default App;
